from urllib.parse import quote_plus
from django.template import Library
from django.urls import reverse

register = Library()


@register.simple_tag()
def url_plus(request, name, *args, **kwargs):
    """
    给url添加redirect参数（上次url） && 将其转义，避免因为'?'而产生起义
    :param request: 略
    :param name: 要去的url的name
    :param args: 要去的url中的uid（不是?后面的参数）
    :param kwargs: 同上
    :return: '要去的url及其参数'?redirect='上次url及其参数'
    """
    # 要去的url
    to_url = reverse(name, args=args, kwargs=kwargs)

    # 将上此url转义
    last_url = request.get_full_path()
    transitioned_last_url = quote_plus(last_url)

    return f"{to_url}?redirect={transitioned_last_url}"


@register.simple_tag()
def forloop_counter(request, counter, page_size=10):
    """
    保证分页后id的正常显示
    :param request:
    :param counter: 计数器（该页中的第几个）
    :param page_size:
    :return:
    """
    page = request.GET.get("page", "1")

    if not page.isdecimal():
        page = 1
    page = int(page)
    if page < 1:
        page = 1

    return (page - 1) * page_size + counter
